/*
 * @Author: 六弦(melodyWxy)
 * @Date: 2022-02-07 17:07:21
 * @LastEditors: 六弦(melodyWxy)
 * @LastEditTime: 2022-02-07 17:25:09
 * @FilePath: /rndemo01/src/components/Swiper/index.js
 * @Description: update here
 */

import React, {Component} from 'react';

import {View, Image} from 'react-native';

import styles from './style';

export default class extends Component {
  state = {
    currentShowIndex: 0,
  };
  autoPlayTimer = null;
  componentDidMount() {
    // auto 轮播
    if (this.props.autoPlay) {
      this.autoPlayTimer = setInterval(() => {
        const {bannerList = []} = this.props;
        const {currentShowIndex} = this.state;
        const nextIndex =
          currentShowIndex === bannerList.length - 1 ? 0 : currentShowIndex + 1;
        this.setState({
          currentShowIndex: nextIndex,
        });
      }, 3000);
    }
  }
  componentWillUnmount() {
    clearInterval(this.autoPlayTimer);
  }
  // 渲染轮播图
  renderBannerImgList = () => {
    const {bannerList = []} = this.props;
    const {currentShowIndex} = this.state;
    return bannerList.map((uri, index) => (
      <Image
        key={uri}
        style={currentShowIndex === index ? styles.bannerImgItem : {opacity: 0}}
        source={{
          uri,
        }}
      />
    ));
  };

  handlePointClick = nextIndex => {
    this.setState({
      currentShowIndex: nextIndex,
    });
  };
  // 渲染轮播图的点点点
  renderBannerPoint = () => {
    const {bannerList = []} = this.props;
    const {currentShowIndex} = this.state;
    return bannerList.map((uri, index) => (
      <View
        key={uri}
        onTouchStart={() => this.handlePointClick(index)}
        style={
          currentShowIndex === index
            ? [styles.bannerPoinit, {left: 150 + 35 * index}, styles.green]
            : [styles.bannerPoinit, {left: 150 + 35 * index}]
        }
      />
    ));
  };

  render() {
    const bannerImgList = this.renderBannerImgList();
    const bannerPoint = this.renderBannerPoint();
    return (
      <View style={styles.swiper}>
        {bannerImgList}
        {bannerPoint}
      </View>
    );
  }
}
